<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card" v-show="showSearch">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="应用名称">
              <el-input v-model="queryParams.applicationName" placeholder="请输入应用名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="平台类型">
              <el-select v-model="queryParams.platformType" placeholder="请选择平台类型" clearable>
                <el-option v-for="item in appTypeOptions" :label="item.name" :key="item.id" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="版本号">
              <el-input v-model="queryParams.version" placeholder="请输入版本号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="激活状态">
              <el-select v-model="queryParams.isActive" placeholder="请选择激活状态" clearable>
                <el-option label="未激活" value="0" />
                <el-option label="已激活" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>

      </el-form>
    </el-card>
    <!-- 数据表格区域 -->
    <el-card class="mt-1">

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="fetchAppList"></right-toolbar>
      </el-row>
      <el-table :data="appList" v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="applicationName" label="应用名称" align="center" />
        <el-table-column prop="applicationDescription" label="应用描述" align="center" />
        <el-table-column prop="platformType" label="平台类型" align="center">
          <template #default="{ row }">
            {{ getPlatformTypeLabel(row.platformType) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentVersion" label="当前版本" align="center" />
        <el-table-column prop="previousVersion" label="上一版本" align="center" />
        <el-table-column prop="versionUpdateTime" label="更新时间" align="center" />
        <el-table-column prop="developer" label="开发者" align="center" />
        <el-table-column prop="isActive" label="激活状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isActive === 1 ? 'success' : 'info'">
              {{ row.isActive === 1 ? '已激活' : '未激活' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" align="center">
          <template #default="{ row }">
            <el-button type="text" icon="More" @click="handleView(row)">查看详情</el-button>
            <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
            <el-button type="text" icon="CircleCheck" @click="handlePushVersion(row)">发布</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用名称" prop="applicationName">
          <el-input v-model="form.applicationName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用描述" prop="applicationDescription">
          <el-input v-model="form.applicationDescription" type="textarea" :rows="3" placeholder="请输入应用描述" />
        </el-form-item>
        <el-form-item label="平台类型" prop="platformType">
          <el-select v-model="form.platformType" placeholder="请选择平台类型" style="width: 100%">
            <el-option v-for="item in appTypeOptions" :label="item.name" :key="item.id" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="激活状态" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择激活状态" style="width: 100%">
            <el-option label="未激活" :value="0" />
            <el-option label="已激活" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`应用详情 - ${detailDialog.data.applicationName}`" width="800px">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="应用名称">{{ detailDialog.data.applicationName }}</el-descriptions-item>
            <el-descriptions-item label="应用描述">{{ detailDialog.data.applicationDescription || '无'
            }}</el-descriptions-item>
            <el-descriptions-item label="平台类型">{{ getPlatformTypeLabel(detailDialog.data.platformType)
            }}</el-descriptions-item>
            <el-descriptions-item label="当前版本">{{ detailDialog.data.currentVersion }}</el-descriptions-item>
            <el-descriptions-item label="上一版本">{{ detailDialog.data.previousVersion || '无' }}</el-descriptions-item>
            <el-descriptions-item label="版本更新时间">{{ detailDialog.data.versionUpdateTime || '无' }}</el-descriptions-item>
            <el-descriptions-item label="开发者">{{ detailDialog.data.developer || '无' }}</el-descriptions-item>
            <el-descriptions-item label="激活状态">
              <el-tag :type="detailDialog.data.isActive === 1 ? 'success' : 'info'">
                {{ detailDialog.data.isActive === 1 ? '已激活' : '未激活' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="文件地址">
              <el-link v-if="detailDialog.data.fileUrl" :href="detailDialog.data.fileUrl" target="_blank">
                {{ detailDialog.data.fileUrl }}
              </el-link>
              <span v-else>无</span>
            </el-descriptions-item>
            <el-descriptions-item label="更新说明">
              <pre>{{ detailDialog.data.releaseNotes || '无' }}</pre>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="版本历史">
          <el-table :data="versionHistory" border>
            <el-table-column prop="versionNumber" label="版本号" width="120" align="center" />
            <el-table-column prop="developer" label="开发者" width="120" align="center" />
            <el-table-column prop="updateTime" label="发布时间" width="180" align="center" />
            <el-table-column prop="releaseNotes" label="更新说明" align="center">
              <template #default="{ row }">
                <pre>{{ row.releaseNotes || '无' }}</pre>
              </template>
            </el-table-column>
            <el-table-column label="文件" width="120" align="center">
              <template #default="{ row }">
                <el-link v-if="row.fileUrl" :href="row.fileUrl" target="_blank">
                  下载
                </el-link>
                <span v-else>无</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 发布版本对话框 -->
    <el-dialog v-model="versionDialog.visible" title="发布新版本" width="600px" :close-on-click-modal="false">
      <el-form ref="versionFormRef" :model="versionForm" :rules="versionRules" label-width="100px">
        <el-form-item label="版本号" prop="versionNumber">
          <el-input v-model="versionForm.versionNumber" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="开发者" prop="developer">
          <el-input v-model="versionForm.developer" placeholder="请输入开发者信息" />
        </el-form-item>
        <el-form-item label="更新说明" prop="releaseNotes">
          <el-input v-model="versionForm.releaseNotes" type="textarea" :rows="3" placeholder="请输入更新说明" />
        </el-form-item>
        <el-form-item label="文件上传">
          <UploadFile v-model:file-ids="versionForm.fileId" type="file" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="versionDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitVersion">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'
import {
  getAppTypeList,
  getDropdownList,
  listAppManagement,
  exportAppManagement,
  getAppManagementDetail,
  addAppManagement,
  updateAppInfo,
  pushAppVersion,
  getAppHistory,
  deleteAppManagement
} from '@/api/appCenter/appMgmt'

const showSearch = ref(true)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  applicationName: '',
  platformType: '',
  version: '',
  isActive: ''
})

// 表单数据
const form = reactive({
  applicationId: undefined,
  applicationName: '',
  applicationDescription: '',
  platformType: '',
  isActive: 0
})

// 版本发布表单
const versionForm = reactive({
  applicationId: undefined,
  versionNumber: '',
  developer: '',
  releaseNotes: '',
  fileId: undefined
})

// 下拉选项数据
const appTypeOptions = ref([])
const dropdownOptions = ref([])

// 对话框控制
const dialog = reactive({
  visible: false,
  title: ''
})

const detailDialog = reactive({
  visible: false,
  data: {}
})

const versionDialog = reactive({
  visible: false
})

// 表格数据
const appList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const versionHistory = ref([])
const formRef = ref()
const versionFormRef = ref()

// 表单验证规则
const rules = reactive({
  applicationName: [
    { required: true, message: '请输入应用名称', trigger: 'blur' }
  ],
  platformType: [
    { required: true, message: '请选择平台类型', trigger: 'change' }
  ],
  isActive: [
    { required: true, message: '请选择激活状态', trigger: 'change' }
  ]
})

const versionRules = reactive({
  versionNumber: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  developer: [
    { required: true, message: '请输入开发者信息', trigger: 'blur' }
  ]
})

// 获取平台类型标签
const getPlatformTypeLabel = (type) => {

  return appTypeOptions.value.find(item => item.id === type).name;
}

// 获取下拉选项数据
const fetchDropdownOptions = async () => {
  try {
    const [typeRes, dropdownRes] = await Promise.all([
      getAppTypeList(),
      getDropdownList()
    ])
    appTypeOptions.value = typeRes.data || []

    dropdownOptions.value = dropdownRes.data || []
  } catch (error) {
    console.error('获取下拉选项失败:', error)
    ElMessage.error('获取下拉选项失败')
  }
}

// 获取应用列表
const fetchAppList = async () => {
  try {
    loading.value = true
    const res = await listAppManagement(queryParams)
    appList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取应用列表失败:', error)
    ElMessage.error('获取应用列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchAppList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.applicationName = ''
  queryParams.platformType = ''
  queryParams.version = ''
  queryParams.isActive = ''
  fetchAppList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchAppList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchAppList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增应用'

  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }

  Object.assign(form, {
    applicationId: undefined,
    applicationName: '',
    applicationDescription: '',
    platformType: '',
    isActive: 0
  })
}

// 编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getAppManagementDetail(row.applicationId)
    Object.assign(form, {
      applicationId: res.data.applicationId,
      applicationName: res.data.applicationName,
      applicationDescription: res.data.applicationDescription,
      platformType: res.data.platformType,
      isActive: res.data.isActive
    })

    dialog.visible = true
    dialog.title = '编辑应用'
  } catch (error) {
    console.error('获取应用详情失败:', error)
    ElMessage.error('获取应用详情失败')
  }
}

// 查看详情
const handleView = async (row) => {
  try {
    const [detailRes, historyRes] = await Promise.all([
      getAppManagementDetail(row.applicationId),
      getAppHistory(row.applicationId)
    ])

    detailDialog.data = detailRes.data
    versionHistory.value = historyRes.data || []
    detailDialog.visible = true
  } catch (error) {
    console.error('获取应用详情失败:', error)
    ElMessage.error('获取应用详情失败')
  }
}

// 发布新版本
const handlePushVersion = (row) => {
  versionForm.applicationId = row.applicationId
  versionForm.versionNumber = ''
  versionForm.developer = ''
  versionForm.releaseNotes = ''
  versionForm.fileId = undefined
  versionDialog.visible = true
}

// 文件上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    versionForm.fileId = response.data.fileId
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 文件上传前校验
const beforeUpload = (file) => {
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('上传文件大小不能超过50MB!')
    return false
  }
  return true
}

// 导出按钮
const handleExport = async () => {
  try {
    loading.value = true
    const res = await exportAppManagement(queryParams)

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([res]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '应用管理列表.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除应用 "${row.applicationName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteAppManagement(row.applicationId)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchAppList()
  }).catch(() => { })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (form.applicationId) {
      await updateAppInfo(form)
    } else {
      await addAppManagement(form)
    }

    ElMessage.success('操作成功')
    dialog.visible = false
    fetchAppList()
  } catch (error) {
    console.error('保存应用信息失败:', error)
  }
}

// 提交版本发布
const submitVersion = async () => {
  try {
    await versionFormRef.value.validate()

    await pushAppVersion(versionForm)
    ElMessage.success('版本发布成功')
    versionDialog.visible = false
    fetchAppList()
  } catch (error) {
    console.error('发布版本失败:', error)
  }
}

// 初始化加载数据
onMounted(() => {
  fetchDropdownOptions()
  fetchAppList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.pre-formatted {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
}
</style>